﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _2_AddTwoNumbers
{
    class Program
    {
        static void Main(string[] args)
        {
            //ListNode l1_3 = new ListNode(9);
            //l1_3.next = null;
            //ListNode l1_2 = new ListNode(1);
            //l1_2.next = l1_3;
            //ListNode l1 = new ListNode(6);
            //l1.next = l1_2;

            //    ListNode l2_3 = new ListNode(4);
            //    l2_3.next = null;
            //    ListNode l2_2 = new ListNode(6);
            //    l2_2.next = l2_3;
            //    ListNode l2 = new ListNode(5);
            //    l2.next = l2_2;


            ListNode l1 = new _2_AddTwoNumbers.ListNode(5);
            ListNode l2 = new _2_AddTwoNumbers.ListNode(5);
            AddTwoNumbersWZ(l1, l2);
            
        }


        private static ListNode AddTwoNumbersWZ(ListNode l1, ListNode l2)
        {
            ListNode p1 = l1, p2 = l2, p3;
            ListNode result = new ListNode(0);

            p3 = result;
            int bit = 0;

            while (p1 != null || p2 != null)
            {
                if (p1 != null)
                {
                    bit += p1.val;
                    p1 = p1.next;
                }

                if (p2 != null)
                {
                    bit += p2.val;
                    p2 = p2.next;
                }

                p3.next = new ListNode(bit % 10);
                p3 = p3.next;
                bit /= 10;
            }

            if (bit == 1)
            {
                p3.next = new ListNode(1);
            }

            return result.next;
        }

        private static ListNode AddTwoNumbers(ListNode l1, ListNode l2)
        {
            if (l1 == null) return l1;
            if (l2 == null) return l2;

            int v1 = 0, v2 = 0, carry = 0, sum = 0;

            ListNode head = new ListNode(0);
            ListNode current = head;

            while (l1 != null || l2 != null || carry > 0)
            {
                v1 = l1 == null ? 0 : l1.val;
                v2 = l2 == null ? 0 : l2.val;

                sum = v1 + v2 + carry;
                
                current.next = new ListNode(sum % 10);
                carry = sum / 10;

                current = current.next;

                l1 = (l1==null || l1.next == null) ? null : l1.next;
                l2 = (l2==null || l2.next == null) ? null : l2.next;
            }

            return head.next;
        }
    }

    public class ListNode
    {
        public int val;
        public ListNode next;
        public ListNode(int x) { val = x; }
    }
}
